#coding=utf-8
import time
from flask import Flask, request, Response
import argparse
import falcon
import tensorflow as tf
import io
import re
import os
import json
from datasets import audio
import numpy as np
from hparams import hparams
from infolog import log
from tacotron.synthesizer import Synthesizer
from wsgiref import simple_server
from pypinyin import pinyin, lazy_pinyin, Style
import time

app = Flask(__name__)


parser = argparse.ArgumentParser()
parser.add_argument('--checkpoint', default='pretrained/', help='Path to model checkpoint')
parser.add_argument('--hparams', default='',help='Hyperparameter overrides as a comma-separated list of name=value pairs')
parser.add_argument('--name', help='Name of logging directory if the two models were trained together.')
args = parser.parse_args()
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '0'
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
checkpoint = os.path.join('logs-Tacotron-2', 'taco_' + args.checkpoint)
try:
	checkpoint_path = tf.train.get_checkpoint_state(checkpoint).model_checkpoint_path
	log('loaded model at {}'.format(checkpoint_path))
except:
	raise RuntimeError('Failed to load checkpoint at {}'.format(checkpoint))

synth = Synthesizer()
modified_hp = hparams.parse(args.hparams)
synth.load(checkpoint_path, modified_hp)

def chs_pinyin(text):
	pys = pinyin(text, style=Style.TONE3)
	letter = {"A": "ei1", "B": "bi4", "C": "sei1", "D": "di4", "E": "yi4", "F": "ai2,fu4", "G": "zhei4", "H": "ai4 chi1", "I": "ai4", "J": "zhei4",
			  "K": "kei4", "L": "ai4 o1", "T": "ti4"}
	results = []
	sentence = []
	for i in range(len(pys)):
		if pys[i][0] in letter.keys():
			pys[i][0] = letter[pys[i][0]]
		if pys[i][0][0] == "，" or pys[i][0][0] == "、" or pys[i][0][0] == '·':
			pys[i][0] = ','
		elif pys[i][0][0] == '。' or pys[i][0][0] == "…":
			pys[i][0] = '.'
		elif pys[i][0][0] == '―' or pys[i][0][0] == "――" or pys[i][0][0] == '—' or pys[i][0][0] == '——':
			pys[i][0] = ','
		elif pys[i][0][0] == "；":
			pys[i][0] = ';'
		elif pys[i][0][0] == "：":
			pys[i][0] = ':'
		elif pys[i][0][0] == "？":
			pys[i][0] = '?'
		elif pys[i][0][0] == "！":
			pys[i][0] = '!'
		elif pys[i][0][0] == "《" or pys[i][0][0] == '》' or pys[i][0][0] == '（' or pys[i][0][0] == '）':
			continue
		elif pys[i][0][0] == '“' or pys[i][0][0] == '”' or pys[i][0][0] == '‘' or pys[i][0][0] == '’' or pys[i][0][0] == '＂':
			continue
		elif pys[i][0][0] == '(' or pys[i][0][0] == ')' or pys[i][0][0] == '"' or pys[i][0][0] == '\'':
			continue
		elif pys[i][0][0] == ' ' or pys[i][0][0] == '/' or pys[i][0][0] == '<' or pys[i][0][0] == '>' or pys[i][0][0] == '「' or pys[i][0][0] == '」':
			continue

		sentence.append(pys[i][0])
		if pys[i][0] in ",.;?!:":
			del(sentence[-1])
			results.append(' '.join(sentence))
			sentence = []

	if len(sentence) > 0:
		results.append(' '.join(sentence))

	for i, res in enumerate(results):
		print(res)

	return results



@app.after_request
def cors(environ):
    environ.headers['Access-Control-Allow-Origin']='*'
    environ.headers['Access-Control-Allow-Method']='*'
    environ.headers['Access-Control-Allow-Headers']='x-requested-with,content-type'
    return environ

@app.route('/synthesize',methods=['GET'])
def synthesize():
	if not request.args.get('text'):
		raise falcon.HTTPBadRequest()
	chs = request.args.get('text')
	print(chs.encode("utf-8").decode("utf-8"))
	pys = chs_pinyin(chs)
	tnum = 0
	ndarray = []
	for p in pys:
		start = time.time()
		result = synth.evals([p])
		ndarray.extend(result.tolist())
		end = time.time()
		print("执行时间: %s seconds" % (end - start))
		tnum += (end-start)
	# return str(tnum)
	return {"data": ndarray}

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=6006)
